package com.weixing.mall.provider.support.mq;

import cn.hutool.core.util.ObjectUtil;
import com.weixing.mall.provider.service.IActivityGoodsService;
import com.weixing.mall.redis.RedisKeyConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyspaceEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName RedisListListener
 * @Description redis监听List变动的监听器--用于并发扣库存
 * @Author Small
 * @Date 2020/4/12 18:14
 * @Version 1.0
 **/
@Component
public class DivideActItemStockRedisListener extends KeyspaceEventMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private TaskExecutor taskExecutor;

    @Autowired
    private IActivityGoodsService activityGoodsService;

    public DivideActItemStockRedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }


    @Override
    protected void doHandleMessage(Message message) {
//        String key = message.toString();
//        System.out.println("接收到List消息：" + key);
//        String preKey = RedisKeyConst.ACT_ITEM_DIVIDE_STOCK_PRE;
//        if (key.startsWith(preKey)) {
//            int start = key.indexOf("::");
//            int end = key.lastIndexOf("::");
//            long actId = Long.parseLong(key.substring(start + 2, end));
//            long itemId = Long.parseLong(key.substring(end + 2));
//
//
//            Object obj = redisTemplate.opsForList().rightPop(key);
//            System.out.println("obj:" + obj);
//            if (ObjectUtil.isNotNull(obj)) {
//
//                int cnt = Integer.parseInt(obj.toString());
//                taskExecutor.execute(() -> this.doDivideStock(actId, itemId, cnt));
//            }
//        }
    }

    private void doDivideStock(long actId, long itemId, int cnt) {
        activityGoodsService.divideStock(actId, itemId, cnt);
    }


}
